package com.project.dao.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.project.dao.RoleDao;
import com.project.dao.bean.Limits;
import com.project.dao.bean.Role;

/**
 * 后台角色管理 Dao Impl
 * @author Sn
 *
 */
public class RoleDaoImpl extends BaseDaoImpl implements RoleDao 
{

	@Override
	public void update(Role role) throws Exception 
	{
		this.getSqlMapClient().update("updateRole", role);
	}

	@Override
	public int save(Role role) throws Exception 
	{
		return add(role);
	}

	@Override
	public List<Role> getRole() throws Exception 
	{
		List<Role> list = this.getSqlMapClient().queryForList("getNewsRole");
        return list;
	}
	
	@Override
	public List<Limits> getRoleLimit(Role role) throws Exception 
	{
		List<Limits> list = this.getSqlMapClient().queryForList("getRoleLimit", role);
		return list;
	}

	@Override
	public void delete(Role role) throws Exception 
	{
		this.getSqlMapClient().update("deleteRole", role);
	}

	@Override
	public List<Role> getRole(Role role) throws Exception 
	{
		List<Role> list = this.queryWithPg("queryRoleByPg", role);
		return list;
	}

	@Override
	public Role getRoleById(Role role) throws Exception 
	{
		return (Role)this.getSqlMapClient().queryForObject("getRoleById",role);
	}

	public static int add(Role role) 
	{
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		int i = 0;
		String ADD = "insert into role(roleName,memo) values (?,?)";
		try 
		{
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/pudu", "root", "123456");
			ps = conn.prepareStatement(ADD);
			ps.setString(1, role.getRoleName());
			ps.setString(2, role.getMemo());
			
			ps.executeUpdate();
			
			ps = conn.prepareStatement("SELECT LAST_INSERT_ID()");
			rs = ps.executeQuery();
			if(rs.next())
			{
				i = rs.getInt(1);
			}
		} catch (ClassNotFoundException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally
		{
			try 
			{
				if(ps!=null)ps.close();
				if(conn!=null)conn.close();
			} catch (SQLException e) 
			{
				e.printStackTrace();
			}
		}
		return i;
	}	

}
